package com.cltech.service.sys.impl;

import com.cltech.dto.AuthorizationDto;
import com.cltech.dto.SysRoleDto;
import com.cltech.dto.TreeNode;
import com.cltech.entity.sys.SysPermission;
import com.cltech.entity.sys.SysRole;
import com.cltech.entity.sys.SysUser;
import com.cltech.frame.base.impl.BaseServiceImpl;
import com.cltech.frame.result.ResponseBean;
import com.cltech.frame.specification.utils.SpecificationSortUtil;
import com.cltech.mapper.SysRoleMapper;
import com.cltech.repository.sys.SysRoleRepository;
import com.cltech.service.sys.SysPermissionService;
import com.cltech.service.sys.SysRoleService;
import com.google.common.base.Splitter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by Administrator on 2019/3/6.
 */
@Service("sysRoleService")
public class SysRoleServiceImpl extends BaseServiceImpl<SysRole, String> implements SysRoleService {

    private SysRoleRepository sysRoleRepository;

    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysPermissionService sysPermissionService;

    @Autowired
    public void setSysUserRepository(SysRoleRepository sysRoleRepository) {
        this.sysRoleRepository = sysRoleRepository;
        super.setBaseRepository(sysRoleRepository);
    }

    @Override
    public ResponseBean<SysRole> findByRoleCode(String roleCode) {
        return ResponseBean.success(sysRoleRepository.findByRoleCode(roleCode));
    }


    @Override
    public Page<SysRoleDto> findAll(Map<String, String[]> queryParameters, int pageNo, int pageSize) {
        Map<String, Object> map = SpecificationSortUtil.creat(queryParameters, SysPermission.class);
        Specification<SysRole> specification = (Specification<SysRole>) map.get(SpecificationSortUtil.SEARCHS);
        Sort sort = (Sort) map.get(SpecificationSortUtil.ORDERS);
        Pageable page = null == sort ? new PageRequest(0, 15) : new PageRequest(0, 15, sort);
        if (null == specification) {
            return sysRoleMapper.entityToDto(sysRoleRepository.findAll(page));
        } else {
            return sysRoleMapper.entityToDto(sysRoleRepository.findAll(specification,
                    page));
        }
    }

    @Override
    @Transactional
    public ResponseBean<SysRole> addOrUpdate(SysRoleDto dto) {
        SysRole sysRole = sysRoleMapper.dtoToEntity(dto);
        String id = sysRole.getId();
        String roleCode = sysRole.getRoleCode();
        if (StringUtils.isEmpty(id)) {
            if (null != findByRoleCode(roleCode).getData()) {
                return ResponseBean.fail("角色编码已存在，新增角色失败");
            }
            sysRole.setCreateTime(new Date());
            return save(sysRole);
        } else {
            SysRole sysRoleOld = findById(id).getData().orElse(null);
            if (null != sysRoleOld) {
                sysRoleOld.setUpdateTime(new Date());
                sysRoleOld.setDescription(sysRole.getDescription());
                sysRoleOld.setName(sysRole.getName());
                if (!sysRole.getRoleCode().equals(sysRoleOld.getRoleCode())) {
                    if (null != findByRoleCode(roleCode).getData()) {
                        return ResponseBean.fail("角色编码已存在，编辑角色失败");
                    }
                    sysRoleOld.setRoleCode(sysRole.getRoleCode());
                }
                return save(sysRoleOld);
            }
            return ResponseBean.fail("更新角色失败");
        }
    }

    @Override
    @Transactional
    public ResponseBean<Void> delete(String id) {
        SysRole sysRole = findById(id).getData().orElse(null);
        if (null == sysRole) {
            return ResponseBean.fail("删除失败,该角色不存在");
        } else {
            if (!CollectionUtils.isEmpty(sysRole.getPermissions())) {
                return ResponseBean.fail("删除失败,请先删除该角色下权限资源");
            }
            if (!CollectionUtils.isEmpty(sysRole.getUsers())) {
                return ResponseBean.fail("删除失败,请先删除该角色下用户");
            }
        }
        deleteById(id);
        return ResponseBean.success("删除成功");
    }

    @Override
    public ResponseBean<Set<SysRole>> findByIds(List<String> ids) {
        return ResponseBean.success(sysRoleRepository.findByIdIsIn(ids));
    }

    @Override
    public ResponseBean<Void> authorization(AuthorizationDto authorizationDto) {
        SysRole sysRole = findById(authorizationDto.getRoleId()).getData().orElse(null);
        if (null == sysRole) {
            return ResponseBean.fail("未找到该角色，授权失败");
        }
        String sysPermissionIds = authorizationDto.getSysPermissionIds();
        if (StringUtils.isEmpty(sysPermissionIds)) {
            return ResponseBean.fail("权限资源不能为空，授权失败");
        }
        Set<SysPermission> sysPermissions = sysPermissionService.findByIdIsIn(Splitter.on(",")
                .trimResults().splitToList(sysPermissionIds)).getData();
        if (CollectionUtils.isEmpty(sysPermissions)) {
            return ResponseBean.fail("未找到权限资源，授权失败");
        }
        sysRole.setPermissions(sysPermissions);
        save(sysRole);
        return ResponseBean.success("授权成功");
    }
}
